<template>
  <div class="relative">
    <div class="heard-right">
      <stageList
        width="250px"
        class="inline mr10"
        @stageCallback = 'stageCallback'></stageList>
      <span>更新日期：</span>
      <zz-select
        class="inline"
        :border= true
        :options="{width: '120px'}"
        :option="dayList"
        :name = dayName
        @optionClick="dayCallback"></zz-select>
      <button v-show="boardSetupMaintain" class="button-block mr10" @click="visible = true">上传全景图片</button>
      <button v-show="boardSetupMaintain" class="button-block mr10" @click="publishPanorama(1)">预览</button>
      <button v-show="boardSetupMaintain" class="button-block" @click="publish(2)">发布</button>
    </div>
    <div ref="rightArea" style="user-select: none;">
      <img ref="imgPic" v-if="imgPic" :src="imgPic" style="width: 100%; height: 100%; position: relative; z-index: 0">
      <div v-for="(item, index) in labelList"
           class="label-list horn ellipsis"
           ref="label"
           :id="item.buildingProgressId"
           :style="{left: `${item.labelLeft}px`, top: `${item.labelTop}px`}" v-dragmove>
        <p class="ellipsis" style="width: 130px;">
          <i v-if="item" class="iconfont icon-dingweiweizhi iconClick" :class="{defaultColor: item.isShow === 1}" @click="changeStatus(item.isShow, index)" style="font-size: 20px;"></i>
          <span v-tooltip="item.tooltip" style="font-size: 16px;">{{item.tooltip}}</span>
        </p>
      </div>
    </div>
    <uploadPic
      :stageId = "stageId"
      :stageName = "stageName"
      :visible="visible"
      @close="close()"
      @addSuccess="addSuccess">
    </uploadPic>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  export default {
    name: '',
    data () {
      return {
        stageId: null,
        stageName: '',
        count: 1,
        dayList: {},
        dayName: "",
        dayId: "",
        visible: false,
        file: '',
        picUuid: '',
        imgPic: '',
        labelList: [],
        backlabelList: [],
        tempwindow: '',
        boardSetupMaintain: false
      }
    },
    directives: {
      dragmove: {
        // 指令的定义
        inserted: function (el, binding, vnode) {
          let oDiv = el
          let moveDiv = el
          let patent = binding.modifiers.patent
          if (patent) {
            moveDiv = el.parentElement
          }
          oDiv.onmousedown = function (e) {
            let l = e.clientX - moveDiv.offsetLeft
            let t = e.clientY - moveDiv.offsetTop
            document.onmousemove = function (e) {
              moveDiv.style.left = e.clientX - l + 'px'
              moveDiv.style.top = e.clientY - t + 'px'
            }
            oDiv.onmouseup = function () {
              document.onmousemove = null
              oDiv.onmouseup = null
            }
          }
        }
      }
    },
    watch: {
      picUuid (val) {
        if (val) {
          this.$store.dispatch({
            type: 'downFile',
            fileUuid: val,
            td: 1
          }).then(res => {
            this.imgPic = res
          })
        } else {
          this.imgPic = ''
        }
      },
      stageId (val) {
        this.getdayList(val)
      },
      dayId (val) {
        if (val) {
          this.getlabelList(val)
        } else {
          this.labelList = []
          this.picUuid = ''
        }
      }
    },
    components: {
      uploadPic (resolve) {
        require(['./upload.vue'], resolve)
      }
    },
    computed: {
      ...mapGetters({
        stageList: 'getstageList',
        stageListDefault: 'getstageListDefault'
      })
    },
    mounted () {
      this.$nextTick(() => {
        this.query()
      })
      this.getAuth()
    },
    methods: {
      getAuth () {
        let menus = this.$local.get('childMenus')
        if (menus) {
          this.boardSetupMaintain = menus.some((item) => item.funCode === 'p_BoardSetup_Panorama_maintain')
        }
      },
      query () {
        this.stageId = this.stageListDefault.stageId
        this.stageName = this.stageListDefault.stageName
      },
      addSuccess () {
        this.getdayList(this.stageId)
      },
      // 获取更新日期列表
      getdayList (val) {
        let data = {
          'stageId': val
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.videoServer}/api/gddnMonitorService/queryUpdateTimeList`,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            if (res.data.data.length > 0) {
              this.dayList = {}
              res.data.data.forEach((x, index) => {
                this.dayList[x.panoramaId] = x.phoneDate
                if (index === 0) {
                  this.dayName = x.phoneDate
                  this.dayId = x.panoramaId
                }
              })
            } else {
              this.dayList = {}
              this.dayName = ''
              this.dayId = ''
            }
          }
        })
      },
      // 获取标签列表
      getlabelList (val) {
        let data = {
          'stageId': this.stageId,
          'panoramaId': val
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.videoServer}/api/gddnMonitorService/queryProjectSectionAndBuildingList`,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            this.labelList = []
            this.picUuid = res.data.data.fileUuid
            if (res.data.data.buildingProgressList) {
              res.data.data.buildingProgressList.forEach((x,index) => {
                let obj = {}
                Object.assign(obj, {buildingProgressId: x.buildingProgressId})
                Object.assign(obj, {buildingName: x.buildingName})
                Object.assign(obj, {sectionName: x.sectionName})
                Object.assign(obj, {tooltip: `${x.buildingName},${x.sectionName}`})
                Object.assign(obj, {isShow: x.isShow})
                if (!x.xCoord) {
                  this.setDefaultStyle(obj, index)
                } else {
                  Object.assign(obj, {labelLeft: x.xCoord})
                  Object.assign(obj, {labelTop: x.yCoord})
                }
                this.labelList.push(obj)
              })
            }
          }
        })
      },
      // 设置标签默认位置
      setDefaultStyle (obj ,index) {
        const rect = this.$refs.rightArea.getBoundingClientRect().width
        this.count = Number.parseInt((rect - 20 )/ 160)
        Object.assign(obj, {labelLeft: `${20 + (index % this.count)*160}`})
        Object.assign(obj, {labelTop: `${20 + Number.parseInt(index / this.count)*60}`})
      },
      // 获取标签位置
      getPosition () {
        this.backlabelList = []
        this.$refs.label.forEach(x => {
          let obj = {}
          Object.assign(obj, {'yCoord': x.offsetTop})
          Object.assign(obj, {'xCoord': x.offsetLeft})
          Object.assign(obj, {'buildingProgressId': x.id})
          this.labelList.map(y => {
            if (x.id === y.buildingProgressId) {
              Object.assign(obj, {'isShow': y.isShow})
            }
          })
          this.backlabelList.push(obj)
        })
      },
      publish () {
        this.$MessageBox({
          showClose: true,
          message: '全景图发布后无法撤销，确认发布本次更新的全景图？',
          type: 'info',
          confirmHanler: () => {
            this.publishPanorama(2)
          }
        })
      },
      // 发布
      publishPanorama (status) {
        if (this.labelList.length > 0) {
          if (status === 1) {
            this.tempwindow = window.open()
          }
          this.getPosition()
          const imgPic = this.$refs.imgPic.getBoundingClientRect()
          let data = {
            'panoramaId': this.dayId,
            'stageId': this.stageId,
            'phoneDate': this.dayName,
            'wide': imgPic.width,
            'height': imgPic.height,
            'status':status,
            'buildingProgressStatusList': JSON.stringify(this.backlabelList)
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/gddnMonitorService/publishPanorama`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              if (status === 1) {
                this.showPreview()
              } else {
                this.$message.success('发布成功！')
              }
            }
          })
        } else {
          if (!this.picUuid) {
            this.$message.error('暂无全景图，请先上传全景图！')
          } else {
            this.$message.error('暂无楼栋，请先添加楼栋！')
          }
        }
      },
      close () {
        this.visible = false
      },
      stageCallback (val) {
        this.stageId = Number.parseInt(val.key)
        this.stageName = val.value
      },
      dayCallback (item) {
        this.dayId = item.key
        this.dayName = item.value
      },
      showPreview () {
        const userInfo = JSON.parse(this.$getCookie('currentUser'))
        Object.assign(userInfo, {stageId: this.stageId})
        this.$setCookie('currentUser', JSON.stringify(userInfo), {expires: 14, domain: this.$site.domain})
        this.tempwindow.location=`${this.$site.videoServer}/#/panoramagramPreview?stageId=${this.stageId}&dateTime=${this.dayName}`
      },
      // 控制大屏是否显示
      changeStatus (isShow ,index) {
        let message
        if (isShow === 1) {
          message = '是否取消该楼栋在大屏的显示？'

        } else {
          message = '是否使该楼栋在大屏中显示？'
        }
        this.$MessageBox({
          showClose: true,
          message: message,
          type: 'info',
          confirmHanler: () => {
            if (isShow === 1) {
              this.labelList[index].isShow = 2
            } else {
              this.labelList[index].isShow = 1
            }
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .heard-right{
    position: absolute;
    top: -42px;
    right: 20px;
  }
  .iconClick{
    cursor: pointer;
    &:hover{
      color: $color;
    }
  }
  .defaultColor{
    color: $color
  }
  .label-list{
    position: absolute;
    z-index: 1;
    opacity:0.9;
    width: 140px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: #fff;
    cursor: move;
    box-shadow: 2px -2px 2px rgba(0,0,0,0.2);
  }
  .horn:after {
    position: absolute;
    display: inline-block;
    top: 32px;
    right: 65px;
    width: 0;
    height: 0;
    content: '';
    border-style: solid;
    border-width: 6px;
    border-color: #fff #fff transparent transparent;
    transform: rotate(135deg);
    box-shadow: 2px -2px 2px rgba(0,0,0,0.2);
  }
</style>
